package com.mouse.magent.web.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mouse.magent.common.exception.BaseException;
import com.mouse.magent.web.entity.common.JwtInfo;
import com.mouse.magent.web.entity.po.User;
import com.mouse.magent.web.entity.pr.LoginPr;
import com.mouse.magent.web.entity.vo.LoginVo;
import com.mouse.magent.web.mapper.UserMapper;
import com.mouse.magent.web.util.BeanUtil;
import com.mouse.magent.web.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.UUID;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public LoginVo login(LoginPr loginPr) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, loginPr.getUsername()));
        if (user == null) throw new BaseException("账号不存在");
        if (!user.getPassword().equals(loginPr.getPassword())) throw new BaseException("密码错误");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, 48);
        JwtInfo jwtInfo = new JwtInfo().setId(user.getId()).setUsername(user.getUsername()).setName(user.getName()).
                setJti(UUID.randomUUID().toString()).setExp(calendar.getTimeInMillis() / 1000);
        String jwt = JwtUtil.generateToken(jwtInfo);
        return BeanUtil.copyObject(user, LoginVo.class).setJwt(jwt);
    }
}
